package com.dingdang.shiro;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {
    //将shiro的过滤器链放入spring容器中
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Autowired DefaultWebSecurityManager defaultWebSecurityManager) {
        //创建过滤器工厂类
        ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
        factoryBean.setSecurityManager(defaultWebSecurityManager);
        //添加shiro内置的过滤器
        /*
         * 常用的过滤器
         * anon：无需登陆就可以访问
         * authc：必须登陆才可以访问
         * perms：登录后还要有权限才能访问
         * role：登录后要有角色才能访问
         * */
        Map<String, String> filterMap = new LinkedHashMap<>();
        //key是url，value就是设置url所对应的过滤器
        filterMap.put("/**", "anon");
        factoryBean.setFilterChainDefinitionMap(filterMap);
        return factoryBean;
    }

    //将安全管理器放入spring容器
    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(@Autowired LoginRealm loginRealm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //关联自定义的realm类
        securityManager.setRealm(loginRealm);
        return securityManager;
    }

    //将realm类放入spring容器
    @Bean
    public LoginRealm loginRealm(@Autowired HashedCredentialsMatcher hashedCredentialsMatcher) {
        LoginRealm loginRealm = new LoginRealm();
        loginRealm.setCredentialsMatcher(hashedCredentialsMatcher);
        return loginRealm;
    }

    //开启shiro的密码加密
    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher() {
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        //设置加密方式
        matcher.setHashAlgorithmName("MD5");
        //撒盐次数（加密次数）
        matcher.setHashIterations(10);
        //设置编码
        matcher.setStoredCredentialsHexEncoded(true);
        return matcher;
    }

}
